//
//  YFEquipmentCalibrationVC.m
//  SquashSpark
//
//  Created by Coollang on 2017/12/5.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "YFEquipmentCalibrationVC.h"
#import "PNCircleChart.h"
#import "YFSearchController.h"
#import "NSAttributedString+RichText.h"
#import "YFSetUpViewController.h"

@interface YFEquipmentCalibrationVC ()
@property (weak, nonatomic) IBOutlet UIView *foreHandProgressSuperView;
@property (weak, nonatomic) IBOutlet UIView *backHandProgressSuperView;
@property (weak, nonatomic) IBOutlet UIButton *skipButton;
@property (weak, nonatomic) IBOutlet UILabel *bottomLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomLabelCon;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *skipBottomCon;
@property (weak, nonatomic) IBOutlet UILabel *foreSwingLabel;
@property (weak, nonatomic) IBOutlet UILabel *backSwingLabel;

/** 正手进度 */
@property (nonatomic, strong) PNCircleChart *forehandCircleView;
/** 反手进度 */
@property (nonatomic, strong) PNCircleChart *backhandCircleView;



@property (nonatomic, assign) NSInteger forehandSwingCount;
@property (nonatomic, assign) NSInteger backhandSwingCount;

@end

@implementation YFEquipmentCalibrationVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setUpUi];
    [self regiesterNotification];
    self.yfBaseDelegate = self;
    
}

- (void)customBaseBackNavBarItemAction:(UIBarButtonItem *)backItem {
    if (self.presentingViewController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        if (self.isWecomeEquipmentVc == NO) {
            BOOL haveSetVc = NO;
            for (UIViewController *childVc in self.navigationController.viewControllers) {
                if ([childVc isKindOfClass:[YFSetUpViewController class]]) {
                    haveSetVc = YES;
                    [self.navigationController popToViewController:childVc animated:YES];
                    break;
                }
            }
            if (haveSetVc == NO) {
               [self.navigationController popViewControllerAnimated:YES];
            }
        }else {
             [self.navigationController popViewControllerAnimated:YES];
        }
       
    }
}


- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    [self.foreHandProgressSuperView layoutIfNeeded];
    [self.backHandProgressSuperView layoutIfNeeded];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self configuerPncircelView];
    });
}
- (void)regiesterNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceConnectHandel) name:kLGPeripheralDidConnect object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceDidDisconnectHandle) name:kLGPeripheralDidDisconnect object:nil];
}

- (void)deviceConnectHandel {
    [self newFounctionUpdateUI];
}

- (void)deviceDidDisconnectHandle {
    [self newFounctionUpdateUI];
}

- (void)openSearchDevice {
    [YFSensorManager openSensorControllrWithVc:self isNecessaryOpenSensorVc:NO];
}

- (void)newFounctionUpdateUI {
    BOOL isConnect = [YFCommunicationManager shareInstance].isPeripheralConnected;
    self.bottomLabelCon.priority = isConnect ? 999:333;
    self.skipBottomCon.priority = isConnect ? 333:999;
    [UIView animateWithDuration:0.35 animations:^{
        self.bottomLabel.alpha = isConnect;
        self.skipButton.alpha = !isConnect;
        [self.bottomLabel layoutIfNeeded];
        [self.skipButton layoutIfNeeded];
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        self.bottomLabel.hidden = !isConnect;
        self.skipButton.hidden = isConnect;
    }];
}

- (void)oldFounctionSetUpUI {
    self.bottomLabelCon.priority = self.isWecomeEquipmentVc ? 333:999;
    self.bottomLabel.hidden = self.isWecomeEquipmentVc;
    self.skipButton.hidden = !self.isWecomeEquipmentVc;
    self.skipBottomCon.priority = self.isWecomeEquipmentVc ? 999:333;
}

- (void)setUpUi {
    self.title = @"Equipment Calibration";
    [self newFounctionUpdateUI];
    self.foreHandProgressSuperView.backgroundColor = [UIColor clearColor];
    self.backHandProgressSuperView.backgroundColor = [UIColor clearColor];
    [self.skipButton clipsCornerRadius:3];
    //自适应字体
    self.bottomLabel.font = kOpenSansFont(OpenSansRegular, 15);
    self.backSwingLabel.font = kOpenSansFont(OpenSansExtraBold, 14);
    self.foreSwingLabel.font = kOpenSansFont(OpenSansExtraBold, 14);
    NSString *foreString = @"0/10";
    NSString *subOneStr = @"0/";
    UIFont *bigFont = kOpenSansFont(OpenSansExtraBold, 29);
    UIFont *smallFont = kOpenSansFont(OpenSansExtraBold, 14);
    NSAttributedString *attr = [NSAttributedString attributedString:foreString subStringRanage:@[[NSValue valueWithRange:[foreString rangeOfString:subOneStr]],[NSValue valueWithRange:NSMakeRange(subOneStr.length, 2)]] colors:@[kYellowGreenColor,kTWhiteText] fonts:@[bigFont,smallFont]];
    self.foreSwingLabel.attributedText = attr;
    self.backSwingLabel.attributedText = attr;
    
    if (self.isWecomeEquipmentVc) {
        self.bottomLabel.text = @"Save the connection state of the sensor, wave the racket of your wall, and complete the calibration of your equipment";
    }else {
       self.bottomLabel.text = @"Save the connection state of the sensor, wave the racket of your wall, and complete the calibration of your equipment";
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self enterRealTimeModel];
}

- (void)configuerPncircelView {
    if (_forehandCircleView == nil) {
        self.forehandCircleView = [self creatpncircleChartView];
        [self.foreHandProgressSuperView addSubview:self.forehandCircleView];
    }
    if (_backhandCircleView == nil) {
        self.backhandCircleView = [self creatpncircleChartView];
        [self.backHandProgressSuperView addSubview:self.backhandCircleView];
    }
}
- (PNCircleChart *)creatpncircleChartView {
    PNCircleChart *pncircleView = [[PNCircleChart alloc] initWithFrame:self.foreHandProgressSuperView.bounds total:@10 current:@0 clockwise:YES shadow:YES shadowColor:[UIColor colorWithWhite:1 alpha:0.4]];
    pncircleView.chartType = PNChartFormatTypeNone;
    pncircleView.strokeColor = kYellowGreenColor;
    pncircleView.lineWidth = @6;
    pncircleView.displayCountingLabel = NO;
    pncircleView.circle.lineCap = kCALineCapRound;
    pncircleView.showProgressAni = NO;
    [pncircleView strokeChart];
    return pncircleView;
}

- (IBAction)skipBtnClick:(id)sender {
    [self openSearchDevice];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self quitRealTimeModel];
}

// 进入实时模式
- (void)enterRealTimeModel {
    [[YFCommunicationManager shareInstance] enterRealTimeModel:^(BOOL success, NSError *error) {
        if (success) {
            [self.hud showString:@"Ready to complete,Please Swing" dimissAfterSecond:3.0];
        }
    } realTimeDataCallBlock:^(BOOL success, SportPoseType actionType, NSInteger speed, float strength, NSInteger swingTime, NSInteger hitBallTime, BOOL hitball, NSInteger areaValue, HandDirectionType handType, ServeDirectionType serveDirectionType, JCHandBallType handBallType, NSTimeInterval timeStamp) {
        
        if (success) {
            UIFont *bigFont = kOpenSansFont(OpenSansExtraBold, 29);
            UIFont *smallFont = kOpenSansFont(OpenSansExtraBold, 14);
            if (handType == HandDirectionTypeForeward) {
                self.forehandSwingCount += 1;
                [self.forehandCircleView updateChartByCurrent:@(self.forehandSwingCount)];
                [self.forehandCircleView strokeChart];
                NSString *foreString = [NSString stringWithFormat:@"%zd/10",self.forehandSwingCount];
                NSString *subOneStr = [NSString stringWithFormat:@"%zd/",self.forehandSwingCount];
                
                NSArray *rangeArr = @[[NSValue valueWithRange:[foreString rangeOfString:subOneStr]], [NSValue valueWithRange:NSMakeRange(subOneStr.length,foreString.length - subOneStr.length)]];
                self.foreSwingLabel.attributedText = [NSAttributedString attributedString:foreString subStringRanage:rangeArr colors:@[kYellowGreenColor,kTWhiteText] fonts:@[bigFont,smallFont]];
                
            }else {
                self.backhandSwingCount += 1;
                [self.backhandCircleView updateChartByCurrent:@(self.backhandSwingCount)];
                [self.backhandCircleView strokeChart];
               
                NSString *backString =  [NSString stringWithFormat:@"%zd/10",self.backhandSwingCount];
                NSString *subOneStr = [NSString stringWithFormat:@"%zd/",self.backhandSwingCount];
                NSArray *rangeArr = @[[NSValue valueWithRange:[backString rangeOfString:subOneStr]], [NSValue valueWithRange:NSMakeRange(subOneStr.length,backString.length - subOneStr.length)]];
                self.backSwingLabel.attributedText = [NSAttributedString attributedString:backString subStringRanage:rangeArr colors:@[kYellowGreenColor,kTWhiteText] fonts:@[bigFont,smallFont]];
            }
            if ([self checkCalibrationCompleation]) {
                // 弹窗提示
                FUIAlertView *alertView = [FUIAlertView alertWithTitle:@"Warm Prompt" message:@"Equipment calibration complete" cancelTitle:nil confirmTitle:@"OK"];
                [alertView show];
                
                [[RLMRealm defaultRealm] beginWriteTransaction];
                [User getUseInfo].equipmentCalibration = YES;
                [[RLMRealm defaultRealm] commitWriteTransaction];
                [alertView setOnOkAction:^{
                    [self quitRealTimeModel];
                    if (self.isWecomeEquipmentVc) {
                        if (self.skipOrNextStepBlock) {
                            self.skipOrNextStepBlock(NO);
                        }
                    }else {
                        [self.navigationController popViewControllerAnimated:YES];
                    }
                }];
            }
        }
    }];
}

// 检查校验是否完成
- (BOOL)checkCalibrationCompleation {
    if (self.forehandSwingCount >= 10 && self.backhandSwingCount >= 10) {
        return YES;
    }
    return NO;
}



//退出实时模式
- (void)quitRealTimeModel {
    [[YFCommunicationManager shareInstance] quitRealTimeModelCompleted:^(BOOL success) {
        
    }];
}

@end

